package edu.purdue.cs.aggr;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import edu.purdue.cs.aggr.message.MessageListener;
import edu.purdue.cs.aggr.message.MessageSender;

public abstract class Node implements Runnable, Externalizable
{
  protected MessageSender sender = null;
  protected MessageListener listener = null;
  private String IP = null;
  private int port;
  private String id;
  protected String controllerId;

  public Node(String IP, int port, boolean usesSockets)
  {
    this.setIP(IP);
    this.setPort(port);
    id = createId(IP, port);
    if (usesSockets) {
      sender = new MessageSender(id);
      setListener(new MessageListener(this));
      new Thread(listener).start();
    }
  }

  public String getId()
  {
    return id;
  }

  public void setId(String id)
  {
    this.id = id;
  }

  public MessageSender getSender()
  {
    return sender;
  }

  public void setSender(MessageSender sender)
  {
    this.sender = sender;
  }

  public static String createId(String IP, int port)
  {
    return IP + ":" + port;
  }

  public static String extractIP(String ID)
  {
    System.out.println("Extracting IP from :" + ID);
    String IP = ID.split(":")[0].trim();
    return IP;
  }

  public int extractPort(String ID)
  {
    return Integer.parseInt(ID.split(":")[1].trim());
  }

  public String getIP()
  {
    return IP;
  }

  public void setIP(String iP)
  {
    IP = iP;
  }

  public int getPort()
  {
    return port;
  }

  public void setPort(int port)
  {
    this.port = port;
  }

  public MessageListener getListener()
  {
    return listener;
  }

  public void setListener(MessageListener listener)
  {
    this.listener = listener;
  }

  public String getControllerId()
  {
    return controllerId;
  }

  public void setControllerId(String controllerId)
  {
    this.controllerId = controllerId;
  }
  
  @Override
  public void writeExternal(ObjectOutput out) throws IOException {
    out.writeObject(IP);
    out.writeObject(port);
    out.writeObject(id);
    out.writeObject(controllerId);
  }

  @Override
  public void readExternal(ObjectInput in) throws IOException,
      ClassNotFoundException {
    IP = (String) in.readObject();
    port = (Integer) in.readObject();
    id = (String) in.readObject();
    controllerId = (String) in.readObject();
  }
}
